/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.system;

import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.core.option.Options;
import cn.hg.jfsa.manage.service.JfsaOptionService;
import cn.hg.jfsa.model.JfsaAdmin;

/**
 * @author Golly
 */
public class JfsaCdnOptionController extends BaseController {

	@Inject
	private JfsaOptionService optionService;

	/*
	 * (non-Javadoc)
	 * @see cn.hg.base.jfinal.controller.BaseController#index()
	 */
	@Override
	public void index () {
		this.loadAllOption();
	}

	@Before (EvictInterceptor.class)
	@CacheName ("option")
	public void save () {
		Enumeration<String> names = this.getParaNames();
		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		Date now = new Date();

		while (names.hasMoreElements()) {
			String key = names.nextElement();
			String value = this.getPara(key);
			int ret =
				Db.update("update jfsa_option set value=?, editor_id=?, edited_time=? where `key`=? and `value` <> ?",
					value, currAdmin.getId(), now, key, value);

			if (ret > 0) {
				Options.set(key, value);
			}

		}

		this.setAttr("flashMsg", "保存成功！");
		this.loadAllOption();
		this.render("index.html");
	}

	private void loadAllOption () {
		Map<String, Object> optionMap = Options.getAll();

		for (String key : optionMap.keySet()) {
			this.setAttr(key, optionMap.get(key));
		}

	}

}
